package org.gm.mybatis.ext.sql;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlQueryUpdate {
	public String dynamicSql(SqlQuery params){
		String sql = params.getSql();
		Pattern pattern = Pattern.compile("#\\{[a-z]*.[a-zA-Z0-9_]*\\}");
		Matcher matcher = pattern.matcher(sql);
		while(matcher.find()){
			String condition = matcher.group();
			condition = condition.substring(2, condition.length() -1);
			String mkey = condition.substring(0, condition.indexOf("."));
			String skey = condition.substring(condition.indexOf(".") + 1);
			boolean replace = true;
			try{
				UUID.fromString((String)params.getArgs().get(skey));
			}catch(Exception ex){
				replace = false;
			}
			if(replace){
				StringBuffer replaceString = new StringBuffer();
				replaceString.append("#{")
					.append(mkey)
					.append(".")
					.append(skey)
					.append(" , jdbcType=OTHER, typeHandler=org.gm.mybatis.ext.typehandler.UUIDTypeHandler}");
				StringBuffer sqlBuffer = new StringBuffer();
				sqlBuffer.append(sql.substring(0, matcher.start()));
				sqlBuffer.append(replaceString.toString());
				sqlBuffer.append(sql.substring(matcher.end()));
				sql = sqlBuffer.toString();
				matcher = pattern.matcher(sql);
			}
		}
		return sql;
	}
}